package com.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.FragmentManager;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.io.Serializable;

/**
 * Created by yubaokang on 2017/2/28.
 */
public abstract class TakePhotoCallBack extends AppCompatDialogFragment implements TakePhoto.TakeResultListener, InvokeListener {

    protected TakePhoto mTakePhoto;
    protected OnChoosePhoneResult result;
    protected InvokeParam invokeParam;
    protected int count;
    protected boolean videoEnable = false;//默认视频不能选

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (mTakePhoto == null) {
            mTakePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return mTakePhoto;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (getDialog() != null)
            getDialog().dismiss();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    public interface OnChoosePhoneResult extends Serializable {
        void onHandlerSuccess(TResult result);

        void onHandlerFailure(String errorMsg);
    }

    @Override
    public void takeSuccess(TResult data) {
        if (result != null) {
            result.onHandlerSuccess(data);
        }
    }

    @Override
    public void takeFail(TResult data, String msg) {
        if (result != null) {
            result.onHandlerFailure(msg);
        }
    }

    @Override
    public void takeCancel() {
    }

    /**
     * 照相
     */
    public void openCamera() {
        final Activity activity = getActivity();
        if (activity == null) return;
        File file = new File(Environment.getExternalStorageDirectory(), "/牛大匠/" + System.currentTimeMillis() + ".jpg");

        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);

        configCompress(mTakePhoto);
        mTakePhoto.setTakePhotoOptions(new TakePhotoOptions.Builder().setWithOwnGallery(true).create());
        mTakePhoto.onPickFromCapture(imageUri);
    }

    boolean isCompress = false;
    int maxSize = 102400;//压缩大小不超过
    int width = 800;//宽
    int height = 800;//高
    boolean isShowProgressBar = true;//是否显示压缩进度条

    public void setCompressEnable(boolean isCompress) {
        this.isCompress = isCompress;
    }

    public void setmaxSizeWH(int maxSize, int width, int height) {
        this.maxSize = maxSize;
        this.width = width;
        this.height = height;
    }

    public void configCompress(TakePhoto takePhoto) {
        if (!isCompress) {
            takePhoto.onEnableCompress(null, false);
            return;
        }
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .create();
        takePhoto.onEnableCompress(config, isShowProgressBar);
    }

    /**
     * 相册-最多9张
     */
    public void openDcimMuti() {
        final Activity activity = getActivity();
        if (activity == null) return;
        configCompress(mTakePhoto);
        mTakePhoto.setTakePhotoOptions(new TakePhotoOptions.Builder().setWithOwnGallery(true).create());
//        if (count > 1) {
            mTakePhoto.onPickMultiple(count, videoEnable);
//            return;
//        }
//        mTakePhoto.onPickFromGallery();
    }

    public static final String Tag = "TakePhotoCallBack";

    /**
     * 底部弹框
     */
    public void show(FragmentManager manager, OnChoosePhoneResult result) {
        this.count = 1;
        this.result = result;
        show(manager, Tag);
    }

    /**
     * 底部弹框
     */
    public void show(FragmentManager manager, int count, OnChoosePhoneResult result) {
        this.count = count;
        this.result = result;
        show(manager, Tag);
    }

    /**
     * 底部弹框
     */
    public void show(FragmentManager manager, int count, boolean videoEnable, OnChoosePhoneResult result) {
        this.count = count;
        this.videoEnable = videoEnable;
        this.result = result;
        show(manager, Tag);
    }
}
